<template>
	<div class="container w96">
		<div class="container_box">
			<div class="container_box_title">医生排班管理</div>
			<div class="container_box_content">
				<el-table :data="pagedTableData" style="width: 98%" v-loading="loading" height="calc(100vh - 230px)" size="small" border>
					<el-table-column prop="name" label="医生名称" width="120" fixed align="center" />
					<el-table-column prop="depart_name" label="科室" width="120" fixed align="center" />
					<el-table-column v-for="dateItem in dateColumns" :key="dateItem.date" :label="dateItem.label" :min-width="240" align="center">
						<!-- 上午列 -->
						<el-table-column :prop="'shang_' + dateItem.date" label="上午" width="120" align="center">
							<template #default="scope">
								<div v-if="scope.row['shang_' + dateItem.date] && scope.row['shang_' + dateItem.date].source > 0" class="source-number">
									{{ scope.row['shang_' + dateItem.date].source }}
									<div style="font-size: 12px; color: #666;">{{ scope.row['shang_' + dateItem.date].time_slot }}</div>
								</div>
								<div v-else>无</div>
							</template>
						</el-table-column>

						<!-- 下午列 -->
						<el-table-column :prop="'xia_' + dateItem.date" label="下午" width="120" align="center">
							<template #default="scope">
								<div v-if="scope.row['xia_' + dateItem.date] && scope.row['xia_' + dateItem.date].source > 0" class="source-number">
									{{ scope.row['xia_' + dateItem.date].source }}
									<div style="font-size: 12px; color: #666;">{{ scope.row['xia_' + dateItem.date].time_slot }}</div>
								</div>
								<div v-else>无</div>
							</template>
						</el-table-column>
					</el-table-column>
					<el-table-column label="操作" width="120" fixed="right" align="center">
						<template #default="scope">
							<el-button size="small" type="primary" plain @click="openScheduleDialog(scope.row)">设置</el-button>
						</template>
					</el-table-column>
				</el-table>

				<!-- 分页 -->
				<el-pagination
					@size-change="handleSizeChange"
					@current-change="handleCurrentChange"
					:current-page="pageParams.page"
					:page-sizes="[10, 20, 50]"
					:page-size="pageParams.limit"
					layout="total, sizes, prev, pager, next, jumper"
					:total="total"
					background
					class="pagination"
					:disabled="loading"
				>
				</el-pagination>
			</div>
		</div>

		<!-- 第一层排班设置弹窗 -->
		<el-dialog v-model="dialogVisible" style="width: 80%" :before-close="handleDialogClose">
			<template #header>
				<div class="dialog-header">
					<el-button type="primary" @click="openSecondDialog">设置排班</el-button>
				</div>
			</template>

			<div class="calendar-container">
				<div
					v-for="dateItem in dateColumns"
					:key="dateItem.date"
					class="calendar-cell"
					:class="{
						selected: isDateSelected(dateItem.date),
						today: isToday(dateItem.date) && !isDateSelected(dateItem.date),
						disabled: isDateDisabled(dateItem.date),
					}"
					@click="selectDate(dateItem.date)"
				>
					<div class="calendar-date">{{ formatDateLabel(dateItem.date) }}</div>
					<div class="calendar-source" v-if="getDateSource(dateItem.date) > 0">号源: {{ getDateSource(dateItem.date) }}</div>
					<div class="calendar-source" v-else>无号源</div>
				</div>
			</div>

			<template #footer>
				<span class="dialog-footer">
					<el-button @click="dialogVisible = false" type="primary">取消</el-button>
				</span>
			</template>
		</el-dialog>

		<!-- 第二层排班详情弹窗 -->
		<div v-if="secondDialogVisible" class="second-dialog-overlay" @click="handleSecondDialogClose">
			<div class="second-dialog" @click.stop style="width: 80%">
				<div class="second-dialog-container">
					<div class="second-dialog-left">
						<div class="calendar-left-header">
							<div class="calendar-left_title fz20">医生的排班详情</div>
							<div class="calendar-left_day fz20">{{ formatFullDate(selectedFullDate) }}</div>
							<div class="left_week fz20">{{ getWeekdayLabel(selectedFullDate) }}</div>
							<div class="calendar-left_time" style="width: 100%; border-bottom: 1px white dashed; padding-bottom: 10px">
								<div style="display: flex; align-items: center; justify-content: space-between">
									<p class="fz20">上午</p>
									<div v-if="isSettingMode">
										<el-switch v-model="morningEnabled" style="--el-switch-on-color: #13ce66" />
									</div>
								</div>
								<div class="calendar-left_info" style="line-height: 36px; font-size: 16px; margin-top: 10px">
									<div v-if="!isSettingMode">
										<div v-if="getDateSlotInfo(selectedFullDate, 'shang')">接诊时间：{{ getDateSlotInfo(selectedFullDate, 'shang').time_slot }}</div>
										<div v-else>接诊时间：无</div>
										<div>号源：{{ morningSource }}</div>
										<div>就诊人数：{{ getDateSlotInfo(selectedFullDate, 'shang') ? getDateSlotInfo(selectedFullDate, 'shang').num : 0 }}</div>
									</div>
									<div v-else>
										<div style="margin-bottom: 10px">
											<el-time-picker
												v-model="morningTimeRange"
												is-range
												range-separator="至"
												start-placeholder="开始时间"
												end-placeholder="结束时间"
												format="HH:mm"
												value-format="HH:mm"
												style="width: 100%"
												:disabled="!morningEnabled"
												popper-class="scheduling-popper"
												:disabled-hours="() => [12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23]"
											/>
										</div>
										<div style="margin-bottom: 10px">
											<el-input
												v-model="morningSourceText"
												placeholder="输入号源"
												:disabled="!morningEnabled"
												style="width: 100%"
												@input="handleMorningSourceInput"
											/>
										</div>
									</div>
								</div>
							</div>
							<div class="calendar-left_time">
								<div style="display: flex; align-items: center; justify-content: space-between">
									<p class="fz20">下午</p>
									<div v-if="isSettingMode">
										<el-switch v-model="afternoonEnabled" style="--el-switch-on-color: #13ce66" />
									</div>
								</div>
								<div class="calendar-left_info" style="line-height: 36px; font-size: 16px; margin-top: 10px">
									<div v-if="!isSettingMode">
										<div v-if="getDateSlotInfo(selectedFullDate, 'xia')">接诊时间：{{ getDateSlotInfo(selectedFullDate, 'xia').time_slot }}</div>
										<div v-else>接诊时间：无</div>
										<div>号源：{{ afternoonSource }}</div>
										<div>就诊人数：{{ getDateSlotInfo(selectedFullDate, 'xia') ? getDateSlotInfo(selectedFullDate, 'xia').num : 0 }}</div>
									</div>
									<div v-else>
										<div style="margin-bottom: 10px">
											<el-time-picker
												v-model="afternoonTimeRange"
												is-range
												range-separator="至"
												start-placeholder="开始时间"
												end-placeholder="结束时间"
												format="HH:mm"
												value-format="HH:mm"
												style="width: 100%"
												:disabled="!afternoonEnabled"
												popper-class="scheduling-popper"
												:disabled-hours="() => [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]"
											/>
										</div>
										<div style="margin-bottom: 10px">
											<el-input
												v-model="afternoonSourceText"
												placeholder="输入号源"
												:disabled="!afternoonEnabled"
												style="width: 100%"
												@input="handleAfternoonSourceInput"
											/>
										</div>
									</div>
								</div>
							</div>
						</div>
					</div>
					<div class="second-dialog-right">
						<div class="calendar-header">
							<el-select
								v-model="selectedMonth"
								placeholder="请选择月份"
								style="width: 25%;margin-left: 20px;"
								@change="handleMonthChange"
								popper-class="scheduling-popper"
							>
								<el-option v-for="month in monthOptions" :key="month.value" :label="month.label" :value="month.value"> </el-option>
							</el-select>
							<div>
								<el-button v-if="isSettingMode" @click="toggleAll" style="margin-right: 10px">反选</el-button>
								<el-button v-if="isSettingMode" @click="saveSchedule">保存排班</el-button>
								<el-button v-else type="primary" @click="enterSettingMode">设置排班</el-button>
							</div>
						</div>
						<div class="calendar-container" style="box-sizing: border-box">
							<div
								v-for="dateItem in currentMonthDates"
								:key="dateItem.date"
								class="calendar-cell"
								:class="{
									selected: isDateSelectedSecond(dateItem.date),
									today: isToday(dateItem.date) && !isDateSelectedSecond(dateItem.date),
									disabled: isDateDisabled(dateItem.date),
								}"
								@click="selectDateSecond(dateItem.date)"
							>
								<div class="calendar-date">{{ formatDateLabel(dateItem.date) }}</div>
								<!-- 修复第二层弹窗显示NaN的问题 -->
								<div class="calendar-source" v-if="getDateSource(dateItem.date) > 0">号源: {{ getDateSource(dateItem.date) }}</div>
								<div class="calendar-source" v-else>无号源</div>
							</div>
						</div>
						<div class="calendar-footer" style="text-align: right">
							<el-button @click="handleSecondDialogClose" type="primary">取消</el-button>
						</div>
					</div>
				</div>
			</div>
		</div>
	</div>
</template>

<script lang="ts" setup>
import { ref, onMounted, reactive, computed } from 'vue';
import { schedulingList, schedulingAdd } from '/@/api/scheduling/index';
import { ElMessage } from 'element-plus';

// 定义表格数据
const tableData = ref<any[]>([]);
const dateColumns = ref<{ date: string; label: string }[]>([]);
const loading = ref(false);

// 分页后的表格数据
const pagedTableData = computed(() => {
	const start = (pageParams.page - 1) * pageParams.limit;
	const end = start + pageParams.limit;
	return tableData.value.slice(start, end);
});

// 弹窗相关
const dialogVisible = ref(false);
const secondDialogVisible = ref(false);
const selectedDate = ref('');
const currentDoctor = ref<any>({});
const doctorScheduleData = ref<any>({});
const currentSchedule = ref<{ shang: number; xia: number }>({ shang: 0, xia: 0 });

// 第二层弹窗新增的响应式数据
const selectedFullDate = ref('');
const morningEnabled = ref(false);
const afternoonEnabled = ref(false);
const morningTimeRange = ref<[string, string]>(['08:00', '09:00']);
const afternoonTimeRange = ref<[string, string]>(['14:00', '15:00']);
const morningSource = ref(0); // 号源
const afternoonSource = ref(0); // 号源
// 添加文本输入框的响应式数据
const morningSourceText = ref('0');
const afternoonSourceText = ref('0');
const isSettingMode = ref(false); // 是否处于设置模式
const selectedMonth = ref('');



// 月份选项
const monthOptions = computed(() => {
	const options = [];
	const now = new Date();
	const currentYear = now.getFullYear();

	for (let i = 0; i < 12; i++) {
		const date = new Date(currentYear, now.getMonth() + i, 1);
		const year = date.getFullYear();
		const month = String(date.getMonth() + 1).padStart(2, '0');
		const value = `${year}-${month}`;
		const label = `${year}年${month}月`;
		options.push({ value, label });
	}
	return options;
});

// 当前月份的日期列表
const currentMonthDates = computed(() => {
	if (!selectedMonth.value) return [];

	const year = parseInt(selectedMonth.value.split('-')[0]);
	const month = parseInt(selectedMonth.value.split('-')[1]) - 1; // JS月份从0开始

	// 获取该月第一天和最后一天
	const firstDay = new Date(year, month, 1);
	const lastDay = new Date(year, month + 1, 0);

	const dates = [];
	for (let day = firstDay.getDate(); day <= lastDay.getDate(); day++) {
		const dateStr = `${selectedMonth.value}-${String(day).padStart(2, '0')}`;
		const dateObj = new Date(year, month, day);
		const weekdays = ['星期日', '星期一', '星期二', '星期三', '星期四', '星期五', '星期六'];
		const weekday = weekdays[dateObj.getDay()];

		dates.push({
			date: dateStr,
			label: `${dateStr} ${weekday}`,
		});
	}

	return dates;
});

// 分页参数
const pageParams = reactive({
	page: 1,
	limit: 10,
});

// 总数
const total = ref(0);

// 获取当前日期（YYYY-MM-DD格式）
const getCurrentDate = () => {
	const date = new Date();
	return date.toISOString().split('T')[0];
};

// 处理月份变化
const handleMonthChange = (value: string) => {
	selectedMonth.value = value;

	// 如果当前选中的日期不在新月份中，则选中该月第一天
	if (selectedFullDate.value && !selectedFullDate.value.startsWith(value)) {
		const firstDay = `${value}-01`;
		selectedFullDate.value = firstDay;
		selectDateSecond(firstDay);
	}
};

// 获取排班列表
const getSchedulingList = async () => {
	try {
		loading.value = true;
		const res: any = await schedulingList({
			page: pageParams.page,
			limit: pageParams.limit,
		}).signIn({
			page: pageParams.page,
			limit: pageParams.limit,
		});

		// 解析接口返回的数据
		if (res.code === 1) {
			// 处理分页数据
			let allData = [];
			if (res.data && typeof res.data === 'object') {
				// 根据接口返回的数据结构调整处理逻辑
				if (Array.isArray(res.data.list)) {
					allData = res.data.list;
					total.value = res.data.total || res.data.count || 0;
				} else if (Array.isArray(res.data.data)) {
					allData = res.data.data;
					total.value = res.data.total || res.data.count || 0;
				} else if (Array.isArray(res.data)) {
					allData = res.data;
					total.value = res.data.length;
				} else {
					allData = [res.data];
					total.value = 1;
				}
			} else {
				allData = [];
				total.value = 0;
			}

			// 提取日期列（只在第一页时提取或当日期列为空时提取）
			if ((pageParams.page === 1 || dateColumns.value.length === 0) && allData.length > 0) {
				// 确保第一个数据项有date字段且是数组
				if (Array.isArray(allData[0].date)) {
					dateColumns.value = allData[0].date.map((date: string) => {
						const dateObj = new Date(date);
						const weekdays = ['星期日', '星期一', '星期二', '星期三', '星期四', '星期五', '星期六'];
						const weekday = weekdays[dateObj.getDay()];
						return {
							date: date,
							label: `${date} ${weekday}`,
						};
					});
				}
			}

			// 重构数据结构以适应表格显示
			const processedData: any[] = [];

			allData.forEach((item: any) => {
				const doctorData: any = {
					id: item.id,
					name: item.name,
					depart_id: item.depart_id,
					depart_name: item.depart_name,
				};

				// 处理上午和下午的排班数据
				if (Array.isArray(item.shang) && Array.isArray(item.xia) && Array.isArray(item.date)) {
					// 确保数组长度一致
					const length = Math.min(item.shang.length, item.xia.length, item.date.length);

					for (let i = 0; i < length; i++) {
						const date = item.date[i];
						const shangItem = item.shang[i];
						const xiaItem = item.xia[i];

						// 上午排班
						if (shangItem) {
							doctorData[`shang_${date}`] = {
								id: shangItem.id,
								doctor_id: shangItem.doctor_id,
								date: shangItem.date,
								time_slot: shangItem.time_slot,
								time: shangItem.time,
								num: shangItem.num,
								status: shangItem.status,
								source: shangItem.source,
								month: shangItem.month,
								edit_time: shangItem.edit_time,
								depart_id: shangItem.depart_id,
							};
						}

						// 下午排班
						if (xiaItem) {
							doctorData[`xia_${date}`] = {
								id: xiaItem.id,
								doctor_id: xiaItem.doctor_id,
								date: xiaItem.date,
								time_slot: xiaItem.time_slot,
								time: xiaItem.time,
								num: xiaItem.num,
								status: xiaItem.status,
								source: xiaItem.source,
								month: xiaItem.month,
								edit_time: xiaItem.edit_time,
								depart_id: xiaItem.depart_id,
							};
						}
					}
				}

				processedData.push(doctorData);
			});

			tableData.value = processedData;
		} else {
			tableData.value = [];
			total.value = 0;
			// 仅在第一页时清空日期列
			if (pageParams.page === 1) {
				dateColumns.value = [];
			}
		}
	} catch (error) {
		console.error('获取排班列表失败:', error);
		tableData.value = [];
		total.value = 0;
		// 仅在第一页时清空日期列
		if (pageParams.page === 1) {
			dateColumns.value = [];
		}
	} finally {
		loading.value = false;
	}
};

// 分页大小改变
const handleSizeChange = (newSize: number) => {
	pageParams.limit = newSize;
	pageParams.page = 1; // 重置为第一页
};

// 当前页改变
const handleCurrentChange = (newPage: number) => {
	pageParams.page = newPage;
};

// 打开第一层排班设置弹窗
const openScheduleDialog = async (row: any) => {
	currentDoctor.value = row;
	dialogVisible.value = true;

	// 构造医生排班数据
	doctorScheduleData.value = {};

	// 遍历日期列，提取该医生在各日期的号源信息
	if (dateColumns.value) {
		dateColumns.value.forEach((dateItem) => {
			const date = dateItem.date;
			const shangSource = row[`shang_${date}`];
			const xiaSource = row[`xia_${date}`];

			// 保存该日期的号源信息 - 确保初始化为数字0而非undefined
			doctorScheduleData.value[date] = {
				shang: shangSource ? Number(shangSource.source) || 0 : 0,
				xia: xiaSource ? Number(xiaSource.source) || 0 : 0,
				shangNum: shangSource ? Number(shangSource.num) || 0 : 0,
				xiaNum: xiaSource ? Number(xiaSource.num) || 0 : 0,
				shangData: shangSource || null,
				xiaData: xiaSource || null,
			};
		});
	}

	// 设置默认选中日期为当前日期，如果当前日期不在列表中则选第一个
	const currentDate = getCurrentDate();
	const currentDateItem = dateColumns.value.find((item) => item.date === currentDate);
	selectedDate.value = currentDateItem ? currentDate : dateColumns.value.length > 0 ? dateColumns.value[0].date : '';
};

// 打开第二层排班详情弹窗
const openSecondDialog = () => {
	if (!selectedDate.value) return;

	// 初始化当前排班数据
	const scheduleData = doctorScheduleData.value[selectedDate.value] || { shang: 0, xia: 0 };
	currentSchedule.value = {
		shang: Number(scheduleData.shang) || 0,
		xia: Number(scheduleData.xia) || 0,
	};

	// 初始化第二层弹窗的数据
	selectedFullDate.value = selectedDate.value;

	// 初始化上午数据
	morningEnabled.value = scheduleData.shang > 0;
	morningSource.value = scheduleData.shang || 0;
	// 初始化上午文本框数据
	morningSourceText.value = String(scheduleData.shang || 0);

	// 设置上午时间范围
	if (scheduleData.shangData && scheduleData.shangData.time_slot) {
		const timeParts = scheduleData.shangData.time_slot.split('-');
		if (timeParts.length === 2) {
			morningTimeRange.value = [timeParts[0], timeParts[1]] as [string, string];
		} else {
			morningTimeRange.value = ['08:00', '09:00'];
		}
	} else {
		morningTimeRange.value = ['08:00', '09:00'];
	}

	// 初始化下午数据
	afternoonEnabled.value = scheduleData.xia > 0;
	afternoonSource.value = scheduleData.xia || 0;
	// 初始化下午文本框数据
	afternoonSourceText.value = String(scheduleData.xia || 0);

	// 设置下午时间范围
	if (scheduleData.xiaData && scheduleData.xiaData.time_slot) {
		const timeParts = scheduleData.xiaData.time_slot.split('-');
		if (timeParts.length === 2) {
			afternoonTimeRange.value = [timeParts[0], timeParts[1]] as [string, string];
		} else {
			afternoonTimeRange.value = ['14:00', '15:00'];
		}
	} else {
		afternoonTimeRange.value = ['14:00', '15:00'];
	}

	// 设置选中的月份
	if (selectedFullDate.value) {
		selectedMonth.value = selectedFullDate.value.substring(0, 7);
	}

	// 重置为非设置模式
	isSettingMode.value = false;

	secondDialogVisible.value = true;
};

// 进入设置模式
const enterSettingMode = () => {
	isSettingMode.value = true;
};

// 反选功能（全部开关反选）
const toggleAll = () => {
	morningEnabled.value = !morningEnabled.value;
	afternoonEnabled.value = !afternoonEnabled.value;
};

// 选择日期（第一层弹窗）
const selectDate = (date: string) => {
	// 如果日期被禁用，则不执行任何操作
	if (isDateDisabled(date)) {
		return;
	}
	selectedDate.value = date;
};

// 选择日期（第二层弹窗）
const selectDateSecond = (date: string) => {
	// 如果日期被禁用，则不执行任何操作
	if (isDateDisabled(date)) {
		return;
	}
	selectedFullDate.value = date;

	// 更新当前排班数据 - 确保数据为数字类型
	const scheduleData = doctorScheduleData.value[date] || { shang: 0, xia: 0 };

	// 更新上午数据
	morningEnabled.value = scheduleData.shang > 0;
	morningSource.value = Number(scheduleData.shang) || 0;
	// 更新上午文本框数据
	morningSourceText.value = String(scheduleData.shang || 0);

	// 更新下午数据
	afternoonEnabled.value = scheduleData.xia > 0;
	afternoonSource.value = Number(scheduleData.xia) || 0;
	// 更新下午文本框数据
	afternoonSourceText.value = String(scheduleData.xia || 0);

	// 退出设置模式
	isSettingMode.value = false;
};

// 判断日期是否被选中（第一层弹窗）
const isDateSelected = (date: string) => {
	return date === selectedDate.value;
};

// 判断日期是否被选中（第二层弹窗）
const isDateSelectedSecond = (date: string) => {
	return date === selectedFullDate.value;
};

// 判断是否是今天
const isToday = (date: string) => {
	return date === getCurrentDate();
};

// 判断日期是否被禁用（早于今天）
const isDateDisabled = (date: string) => {
	return date < getCurrentDate();
};

// 格式化日期为 DD 格式
const formatDateLabel = (date: string) => {
	return date.split('-')[2];
};

// 获取星期几的标签
const getWeekdayLabel = (date: string) => {
	if (!date) return '';
	const dateObj = new Date(date);
	const weekdays = ['周日', '周一', '周二', '周三', '周四', '周五', '周六'];
	return weekdays[dateObj.getDay()];
};

// 格式化日期为完整格式（用于第二层弹窗标题）
const formatFullDate = (date: string) => {
	if (!date) return '';
	const dateObj = new Date(date);
	const year = dateObj.getFullYear();
	const month = String(dateObj.getMonth() + 1).padStart(2, '0');
	const day = String(dateObj.getDate()).padStart(2, '0');
	const weekdays = ['星期日', '星期一', '星期二', '星期三', '星期四', '星期五', '星期六'];
	const weekday = weekdays[dateObj.getDay()];
	return `${year}年${month}月${day}日 ${weekday}`;
};

// 获取指定日期的号源总数，确保返回数字类型
const getDateSource = (date: string) => {
	if (doctorScheduleData.value[date]) {
		const data = doctorScheduleData.value[date];
		// 确保计算结果为数字，避免NaN
		return Number(data.shang) + Number(data.xia) || 0;
	}
	return 0;
};
// 处理上午号源输入
const handleMorningSourceInput = (value: string) => {
	// 只允许数字输入
	const numericValue = value.replace(/[^\d]/g, '');
	morningSourceText.value = numericValue;
	morningSource.value = Number(numericValue) || 0;
};

// 处理下午号源输入
const handleAfternoonSourceInput = (value: string) => {
	// 只允许数字输入
	const numericValue = value.replace(/[^\d]/g, '');
	afternoonSourceText.value = numericValue;
	afternoonSource.value = Number(numericValue) || 0;
};


// 获取指定日期和时间段的详细信息
const getDateSlotInfo = (date: string, time: 'shang' | 'xia') => {
	if (doctorScheduleData.value[date]) {
		const data = doctorScheduleData.value[date];
		return data[`${time}Data`] || null;
	}
	return null;
};

// 保存排班信息
const saveSchedule = async () => {
	if (!selectedFullDate.value || !currentDoctor.value.id) {
		ElMessage.error('缺少必要信息');
		return;
	}

	try {
		// 构造排班数据数组
		const scheduleDataArray = [];

		// 上午排班数据
		if (morningEnabled.value) {
			scheduleDataArray.push({
				date: selectedFullDate.value,
				depart_id: currentDoctor.value.depart_id,
				time_slot: `${morningTimeRange.value[0]}-${morningTimeRange.value[1]}`,
				doctor_id: currentDoctor.value.id,
				time: 1, // 上午
				source: morningSource.value,
				num: morningSource.value, // 使用号源数量作为就诊人数
				month: selectedFullDate.value.substring(5, 7),
				status: 1,
			});
		}

		// 下午排班数据
		if (afternoonEnabled.value) {
			scheduleDataArray.push({
				date: selectedFullDate.value,
				depart_id: currentDoctor.value.depart_id,
				time_slot: `${afternoonTimeRange.value[0]}-${afternoonTimeRange.value[1]}`,
				doctor_id: currentDoctor.value.id,
				time: 2, // 下午
				source: afternoonSource.value,
				num: afternoonSource.value, // 使用号源数量作为就诊人数
				month: selectedFullDate.value.substring(5, 7),
				status: 1,
			});
		}

		// 如果没有启用任何时段，添加一个默认的休息状态排班
		if (scheduleDataArray.length === 0) {
			scheduleDataArray.push({
				date: selectedFullDate.value,
				depart_id: currentDoctor.value.depart_id,
				time_slot: '00:00-00:00',
				doctor_id: currentDoctor.value.id,
				time: 1, // 上午
				source: 0,
				num: 0,
				month: selectedFullDate.value.substring(5, 7),
				status: 0, // 休息
			});
		}

		// 调用接口保存排班信息
		const res = await schedulingAdd({ arr: JSON.stringify(scheduleDataArray) }).signIn({ arr: JSON.stringify(scheduleDataArray) });

		if (res.code === 1) {
			// 保存成功后更新本地数据
			doctorScheduleData.value[selectedFullDate.value] = {
				shang: morningEnabled.value ? morningSource.value : 0,
				xia: afternoonEnabled.value ? afternoonSource.value : 0,
				shangNum: morningEnabled.value ? morningSource.value : 0,
				xiaNum: afternoonEnabled.value ? afternoonSource.value : 0,
			};

			// 刷新表格数据
			await getSchedulingList();

			// 提示成功信息，使用更高的层级
			ElMessage({
				message: '排班设置成功',
				type: 'success',
				duration: 2000,
				showClose: true,
				offset: 40,
				customClass: 'high-z-index-message'
			});

			// 关闭两个弹窗
			secondDialogVisible.value = false;
			dialogVisible.value = false;
			isSettingMode.value = false;
			
			// 更新当前显示的数据
			selectDateSecond(selectedFullDate.value);
		} else {
			ElMessage({
				message: res.msg || '排班保存失败',
				type: 'error',
				duration: 2000,
				showClose: true,
				offset: 40,
				customClass: 'high-z-index-message'
			});
		}
	} catch (error) {
		console.error('保存排班失败:', error);
		ElMessage.error('保存失败，请重试');
	}
};

// 处理第一层弹窗关闭
const handleDialogClose = () => {
	dialogVisible.value = false;
};

// 处理第二层弹窗关闭
const handleSecondDialogClose = () => {
	secondDialogVisible.value = false;
	isSettingMode.value = false;
};

// 组件挂载时获取数据
onMounted(() => {
	getSchedulingList();
});
</script>

<style scoped>
* {
	box-sizing: content-box;
}

.container_box {
	width: 96%;
	height: 100%;
	background: #fff;
	margin-left: 6px;
}

.container_box > .container_box_title {
	font-size: 20px;
	font-weight: 600;
	padding: 16px 20px;
	border-bottom: 1px solid #f5f5f5;
}

.container_box > .container_box_content {
	/* padding: 20px; */
}

.pagination {
	margin-top: 20px;
	text-align: center; /* 修改为居中 */
}

:deep(.el-table) {
	--el-table-header-bg-color: #f5f7fa;
}

:deep(.el-table .cell) {
	line-height: 1.4;
	padding: 4px 10px;
}

.source-number {
	font-size: 16px;
	font-weight: bold;
	color: #409eff;
}

.dialog-header {
	display: flex;
	justify-content: end;
	align-items: center;
	width: 96%;
}

/* 第一层弹窗 */
.first-dialog {
	z-index: 2001 !important;
}

/* 第二层弹窗要高于第一层 */
.second-dialog-overlay {
	position: fixed;
	top: 0;
	left: 0;
	width: 100%;
	height: 100%;
	background-color: rgba(0, 0, 0, 0.5);
	display: flex;
	justify-content: center;
	align-items: center;
	z-index: 2052;
}

.second-dialog {
	background: white;
	border-radius: 4px;
	box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
	display: flex;
	flex-direction: column;
	max-height: 90vh;
	z-index: 2063;
}

.calendar-container {
	display: grid;
	grid-template-columns: repeat(10, 1fr);
	gap: 0; /* 移除格子之间的间距 */
	padding: 20px;
	max-height: 500px;
	overflow-y: auto;
}

.calendar-cell {
	height: 80px;
	display: flex;
	flex-direction: column;
	justify-content: center;
	align-items: center;
	cursor: pointer;
	border: 1px solid #c3e4ff;
	/* border-radius: 4px; */
	transition: all 0.3s;
}

.calendar-cell:hover {
	border-color: #409eff;
	background-color: #ecf5ff;
}

.calendar-cell.selected {
	background-color: #409eff;
	color: white;
	border-color: #409eff;
}

/* 当前日期高亮样式 */
.calendar-cell.today {
	border-color: #409eff;
	background-color: #ecf5ff;
}

.calendar-cell.disabled {
	background-color: #f5f5f5;
	color: #999;
	cursor: not-allowed;
}

.calendar-cell.disabled:hover {
	background-color: #f5f5f5;
	border-color: #c3e4ff;
}

.calendar-date {
	font-size: 18px;
	font-weight: bold;
}

.calendar-weekday {
	font-size: 12px;
	margin: 4px 0;
}

.calendar-source {
	font-size: 12px;
}

.dialog-footer {
	display: flex;
	justify-content: flex-end;
	width: 100%;
}

/* 第二层弹窗排班详情样式 */
.second-dialog-container {
	display: flex;
	height: 600px; /* 与第一层弹窗高度一致 */
}
.calendar-left-header {
	width: 90%;
	color: white;
	> div {
		width: 100%;
		margin-bottom: 10px;
	}
}

.second-dialog-left {
	flex: 0 0 20%;
	background-color: #ff9138;
	padding: 20px 0 20px 20px; /* 左侧无边距，右侧有边距 */
	display: flex;
	flex-direction: column;
}

.second-dialog-controls {
	flex: 1;
	display: flex;
	flex-direction: column;
	gap: 20px;
}

.control-item {
	display: flex;
	flex-direction: column;
	gap: 5px;
	color: white;
}

.control-label {
	font-size: 14px;
	font-weight: bold;
}

.second-dialog-actions {
	display: flex;
	justify-content: center;
}

.second-dialog-right {
	flex: 1;
	padding: 0 20px 0 0; /* 左侧无边距，右侧有边距 */
	display: flex;
	flex-direction: column;
}

.calendar-header {
	padding: 10px 0;
	display: flex;
	justify-content: space-between;
	font-weight: bold;
	font-size: 16px;
}

.second-dialog-right .calendar-container {
	box-sizing: content-box;
}

/* 第二层弹窗日历样式 - 每行7个格子 */
.second-calendar-container {
	grid-template-columns: repeat(7, 1fr); /* 每行7个 */
	overflow-y: auto; /* 允许垂直滚动 */
}

.second-calendar-container .calendar-cell {
	height: calc((100% - 10px) / 3); /* 根据行数调整高度 */
	min-height: 70px;
}

/* 移除右边和底部边框，只保留左边和顶部边框 */
.second-calendar-container .calendar-cell:not(:nth-child(7n)):not(:nth-last-child(-n + 7)) {
	border-right: 1px solid #c3e4ff;
}

.second-calendar-container .calendar-cell:not(:nth-last-child(-n + 7)) {
	border-bottom: 1px solid #c3e4ff;
}

.fz20 {
	font-size: 20px;
}
</style>

<style>
/* 为时间选择器和下拉框设置合适的z-index */
.scheduling-popper {
	z-index: 2052 !important;
}

/* 为消息提示设置更高的层级 */
.high-z-index-message {
	z-index: 3000 !important;
}

/* 移除滚动条 */
::-webkit-scrollbar {
	display: none;
}

/* 为IE和Edge浏览器移除滚动条 */
* {
	-ms-overflow-style: none;
	scrollbar-width: none;
}
</style>
